package ru.amse.tsyganov.jumleditor.graphicaleditor.common;

import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.commands.CommandFactory;
import ru.amse.tsyganov.jumleditor.graphicaleditor.Coordinates;
import ru.amse.tsyganov.jumleditor.graphicaleditor.EditorMode;
import ru.amse.tsyganov.jumleditor.graphicaleditor.GraphicalEditor;
import ru.amse.tsyganov.jumleditor.model.common.State;
import ru.amse.tsyganov.jumleditor.view.common.StateView;
import ru.amse.tsyganov.jumleditor.view.preferences.Cursors;

public abstract class AddStateMode extends EditorMode {
	
	private final GraphicalEditor graphicalEditor;
	
	public AddStateMode(GraphicalEditor graphicalEditor) {
		if (graphicalEditor == null) {
			throw new IllegalArgumentException();
		}
		this.graphicalEditor = graphicalEditor;	
	}
	
	@Override
	public void initState() {
		graphicalEditor.getCanvas().setCursor(
				Cursors.getCursorArrowPlus());
		graphicalEditor.getActivityGraphView().setPaintConnectionPoints(false);
		graphicalEditor.getCanvas().redraw();
	}
	
	@Override
	public void mouseDoubleClick(MouseEvent e) {
	}

	@Override
	public void mouseDown(MouseEvent e) {
		StateView<? extends State> newStateView = createNewState();
		
		newStateView.setX(e.x - newStateView.getWidth() / 2);
		newStateView.setY(e.y - newStateView.getHeight() / 2);
				
		Command newStateCommand = 
			CommandFactory.createNewStateCommand(
					getEditor().getActivityGraphView(),
					newStateView);
		
		newStateView.addPropertyListener(
				graphicalEditor.getPropertyChangeListener());
		
		getEditor().getViewsManager().executeCommand(newStateCommand);
		
		getEditor().getActivityGraphView().getSelectedItems().selectedStatesClear();
		getEditor().getActivityGraphView().getSelectedItems().selectedTransitionsClear();
		
		getEditor().getActivityGraphView().getSelectedItems().selectedStatesAdd(newStateView);
	}
	
	public abstract StateView<? extends State> createNewState();

	@Override
	public void mouseUp(MouseEvent e) {
		graphicalEditor.setEditorMode(graphicalEditor.getSelectionMode());
	}

	@Override
	public void paintControl(PaintEvent e, Coordinates coordinates) {
	}

	@Override
	public void mouseMove(MouseEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
	}

	@Override
	public void keyReleased(KeyEvent e) {	
	}

	protected GraphicalEditor getEditor() {
		return graphicalEditor;
	}
}
